package com.yzx.lifeassistants.model.impl;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Context;

import com.yzx.lifeassistants.bean.JobInfo;
import com.yzx.lifeassistants.model.IQueryJobInfo;
import com.yzx.lifeassistants.model.callback.IQueryJobInfoCB;
import com.yzx.lifeassistants.utils.HttpClientUtil;
import com.yzx.lifeassistants.utils.IHttpCallBack;
import com.yzx.lifeassistants.utils.LogcatUtils;

/**
 * @Description: 查询招聘信息
 * @author: yzx
 * @time: 2016-3-22 下午9:33:50
 */
public class QueryJobInfoImpl implements IQueryJobInfo {

	public static final String TAG = "QueryJobInfoImpl";
	private IQueryJobInfoCB queryCallBack;// 回调

	public QueryJobInfoImpl(Context context, IQueryJobInfoCB queryCallBack) {
		this.queryCallBack = queryCallBack;
	}

	/**
	 * 
	 * @Description: 查询招聘信息
	 */
	@Override
	public void queryJobInfo(String url) {
		HttpClientUtil.sendRequestWithGBK(url, null, new IHttpCallBack() {

			@Override
			public void onFinish(String response) {
				LogcatUtils.i(TAG, response);
				JobInfo jobInfo = new JobInfo();
				if (null == response || "".equals(response)) {
					LogcatUtils.e(TAG, "获取招聘信息详情失败");
					queryCallBack.queryError(IQueryJobInfoCB.RESULR_NULL);
				} else {
					Document doc = Jsoup.parse(response);
					Element titleElement = doc.select("div.content1>h1")
							.first();
					jobInfo.setTitle(titleElement.text());
					Element timeElement = doc.select("div.news-detail").first();
					Elements infoElements = timeElement.select("p>b>font");
					Boolean isTime = true;
					for (Element element : infoElements) {
						if (isTime) {
							jobInfo.setTime(element.text());
							isTime = false;
						} else {
							jobInfo.setPlace(element.text());
						}
					}
					Element detail = doc.select("div.news-entry").first();
					jobInfo.setContent(detail.toString());
					if (haveData(jobInfo.getTitle())
							&& haveData(jobInfo.getTime())
							&& haveData(jobInfo.getPlace())
							&& haveData(jobInfo.getContent())) {
						LogcatUtils.i(TAG, "获取招聘信息详情成功");
						queryCallBack.querySuccess(jobInfo);
					} else {
						LogcatUtils.e(TAG, "获取招聘信息详情失败");
						queryCallBack.queryError(IQueryJobInfoCB.RESULR_NULL);
					}
				}
			}

			@Override
			public void onError(Exception e) {
				LogcatUtils.e(TAG, "获取招聘信息详情异常");
				if (null != e.getMessage()) {
					LogcatUtils.e(TAG, e.getMessage());
				}
				queryCallBack.queryError(IQueryJobInfoCB.QUERY_ERROR);
			}
		});
	}

	/**
	 * 
	 * @Description: 是否有数据
	 */
	private Boolean haveData(String data) {
		if (null == data || "".equals(data)) {
			return false;
		} else {
			return true;
		}
	}
}
